package com.sjx.jtt809.client.business;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.sjx.jtt809.client.business.impl.ResponseClientHandlerImpl_0x1002;
import com.sjx.jtt809.client.business.impl.ResponseClientHandlerImpl_0x9001;
import com.sjx.jtt809.client.business.impl.ResponseClientHandlerImpl_0x9005;
import com.sjx.jtt809.server.pojo.Response;
import com.sjx.jtt809.server.util.ConstantJtt809Util;
import io.netty.channel.ChannelHandlerContext;

import java.util.HashMap;
import java.util.Map;

/**
 * 业务工厂，实例化业务
 */
public class ClientBusinessFactory implements Runnable {

    private static final Log logger = LogFactory.get();

    /**
     * 业务实现方法类
     */
    public static Map<Integer, Class<? extends IClientBusinessServer>> businessMap = new HashMap<Integer, Class<? extends IClientBusinessServer>>();

    static {
        /**
         * 收到：从链路连接保持请求消息（0x9005）
         * 响应：从链路连接保持应答消息（0x9006）
         */
        businessMap.put(ConstantJtt809Util.DOWN_LINKTEST_REQ, ResponseClientHandlerImpl_0x9005.class);

        /**
         * 收到：主链路登录应答消息（0x1002）
         */
        businessMap.put(ConstantJtt809Util.UP_CONNECT_REP, ResponseClientHandlerImpl_0x1002.class);

        /**
         * 收到：从链路连接保持请求消息（0x9001）
         * 响应：从链路连接应答信息（0x9002）
         */
        businessMap.put(ConstantJtt809Util.DOWN_CONNECT_REQ, ResponseClientHandlerImpl_0x9001.class);
    }

    private ChannelHandlerContext ctx;

    private Response msg;

    public ClientBusinessFactory(ChannelHandlerContext ctx, Response msg) {
        this.ctx = ctx;
        this.msg = msg;
    }

    @Override
    public void run() {
        try {
            if (msg == null) {
                throw new RuntimeException("数据包为空！");
            }

            Class<? extends IClientBusinessServer> cls = businessMap.get(msg.getMsgId());

            // 未找到实现方法则返回
            if (cls == null) {
                return;
            }

            // 实例化类
            IClientBusinessServer iBusinessServer = cls.newInstance();
            // 执行业务方法
            iBusinessServer.businessHandler(ctx, msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
